package com.css.zfzx.fxpg.modules.vulnerability.danger.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.preestimate.workspace.repository.entity.FxPreestimateWorkspaceEntity;
import com.css.zfzx.fxpg.modules.preestimate.workspace.viewobjects.FxPreestimateWorkspaceQueryParams;
import com.css.zfzx.fxpg.modules.preestimate.workspace.viewobjects.FxPreestimateWorkspaceVO;
import com.css.zfzx.fxpg.modules.vulnerability.danger.repository.FxVulnerabilityDangerNativeRepository;
import com.css.zfzx.fxpg.modules.vulnerability.danger.repository.FxVulnerabilityDangerRepository;
import com.css.zfzx.fxpg.modules.vulnerability.danger.repository.entity.FxVulnerabilityDangerEntity;
import com.css.zfzx.fxpg.modules.vulnerability.danger.service.FxVulnerabilityDangerService;
import com.css.zfzx.fxpg.modules.vulnerability.danger.viewobjects.FxVulnerabilityDangerQueryParams;
import com.css.zfzx.fxpg.modules.vulnerability.danger.viewobjects.FxVulnerabilityDangerVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author andy
 * @date 2020-12-10
 */
@Service
@Slf4j
public class FxVulnerabilityDangerServiceImpl implements FxVulnerabilityDangerService {

	@Autowired
    private FxVulnerabilityDangerRepository fxVulnerabilityDangerRepository;
    @Autowired
    private FxVulnerabilityDangerNativeRepository fxVulnerabilityDangerNativeRepository;

    @Override
    public JSONObject queryFxVulnerabilityDangers(FxVulnerabilityDangerQueryParams queryParams, int curPage, int pageSize) {
        Page<FxVulnerabilityDangerEntity> fxVulnerabilityDangerPage = this.fxVulnerabilityDangerNativeRepository.queryFxVulnerabilityDangers(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxVulnerabilityDangerPage);
        return jsonObject;
    }


    @Override
    public FxVulnerabilityDangerEntity getFxVulnerabilityDanger(String id) {
        FxVulnerabilityDangerEntity fxVulnerabilityDanger = this.fxVulnerabilityDangerRepository.findById(id).orElse(null);
         return fxVulnerabilityDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityDangerEntity saveFxVulnerabilityDanger(FxVulnerabilityDangerEntity fxVulnerabilityDanger) {
        String uuid = UUIDGenerator.getUUID();
        fxVulnerabilityDanger.setId(uuid);
        fxVulnerabilityDanger.setCreateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityDanger.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxVulnerabilityDangerRepository.save(fxVulnerabilityDanger);
        return fxVulnerabilityDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxVulnerabilityDangerEntity updateFxVulnerabilityDanger(FxVulnerabilityDangerEntity fxVulnerabilityDanger) {
        fxVulnerabilityDanger.setUpdateUser(PlatformSessionUtils.getUserId());
        fxVulnerabilityDanger.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxVulnerabilityDanger.getId();
        FxVulnerabilityDangerEntity one = fxVulnerabilityDangerRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxVulnerabilityDanger, one);
        this.fxVulnerabilityDangerRepository.save(one);
        return fxVulnerabilityDanger;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxVulnerabilityDangers(List<String> ids) {
        List<FxVulnerabilityDangerEntity> fxVulnerabilityDangerList = this.fxVulnerabilityDangerRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(fxVulnerabilityDangerList) && fxVulnerabilityDangerList.size() > 0) {
            for(FxVulnerabilityDangerEntity fxVulnerabilityDanger : fxVulnerabilityDangerList) {
                this.fxVulnerabilityDangerRepository.delete(fxVulnerabilityDanger);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public List<FxVulnerabilityDangerEntity> getFxVulnerabilityDangers(FxVulnerabilityDangerQueryParams queryParams) {
        List<FxVulnerabilityDangerEntity> fxVulnerabilityDangers = this.fxVulnerabilityDangerNativeRepository.listFxVulnerabilityDangers(queryParams);
        return fxVulnerabilityDangers;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxVulnerabilityDangerVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxVulnerabilityDangerVO.class, params);
            List<FxVulnerabilityDangerVO> list = result.getList();
            // 新增
            for (int i = 0; i < list.size(); i++) {
                FxVulnerabilityDangerEntity workspaceEntity = new FxVulnerabilityDangerEntity();
                FxVulnerabilityDangerVO workspaceVO = list.get(i);
                // 将VO数据映射拷贝到库表中
                BeanUtils.copyProperties(workspaceVO, workspaceEntity);
                workspaceEntity.setIsValid("1");
                workspaceEntity.setId(UUID.randomUUID().toString().replace("-",""));
                fxVulnerabilityDangerRepository.save(workspaceEntity);
            }
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxVulnerabilityDangerVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxVulnerabilityDangerVO workspaceVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + workspaceVO.getRowNum() + "行" + workspaceVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }

            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    @Override
    public String exportExcel(FxVulnerabilityDangerQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxVulnerabilityDangerEntity> workspaceEntities = fxVulnerabilityDangerNativeRepository.listFxVulnerabilityDangers(queryParams);
            // 深拷贝
            ArrayList<FxVulnerabilityDangerVO> vos = new ArrayList<>();
            for (FxVulnerabilityDangerEntity workspaceEntity : workspaceEntities) {
                FxVulnerabilityDangerVO vo = new FxVulnerabilityDangerVO();
                BeanUtils.copyProperties(workspaceEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "区划危险性数据管理", "区划危险性数据管理", FxVulnerabilityDangerVO.class, "区划危险性数据管理.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }


}
